﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;
using uTorrentRemote.Net;
using System.Collections.Specialized;
using System.Threading;
using System.IO;

namespace uTorrentRemote.TokenDispatchers
{
    public class AnimeLayerDownloadDispatcher : CommonTokenDispatcher, ITokenDispatcher
    {

        public AnimeLayerDownloadDispatcher(ILog log)
            : base(log)
        {
        }

        public bool TryToken(Token token)
        {
            string url = token.ToString();

            Regex regex = new Regex(@"http\://(www\.)*animelayer\.ru/details\.php\?id=\d\d+(&hit=1)*", RegexOptions.IgnoreCase);

            if (!regex.Match(url).Success)
                return false;

            url = url.ToLower().Replace("www.", ""); // we don't need www-prefix
            url = url.Replace("&hit=1", ""); // we don't need &hit=1 url postfix

            if (!isInitiated)
                init();

            if (urls.ContainsKey(url))
                return false;
            else
            {
                urls[url] = false; // add url with 'not loaded' flag
                log.Write("Added " + url);
            }

            // at this place we have working thread to download urls and update flags

            return true;
        }

        protected override void relogin()
        {
            bool loggedIn = false;

            do
            {
                try
                {
                    client = new WebClientEx();
                    var data = new NameValueCollection
                    {
                        { "username", ConfigurationManager.AppSettings["animelayer_login"] },
                        { "password", ConfigurationManager.AppSettings["animelayer_password"] },
                        { "returnto", "" }
                    };

                    var response1 = client.UploadValues("http://animelayer.ru/takelogin.php", data);
                    string str = Encoding.UTF8.GetString(response1).ToLower();
                    string logged_in_indicator = String.Format(">{0}</span></b>", ConfigurationManager.AppSettings["animelayer_login"]).ToLower();
                    if (str.Contains(logged_in_indicator))
                    {
                        log.Write("OK Logged in to animelayer.ru");
                        loggedIn = true;
                    }
                    else
                    {
                        log.Write("ERROR Can't log in to animelayer.ru (will keep on trying)");
                        Thread.Sleep(60 * 1000); // wait for 1 minute
                    }
                }
                catch (Exception ex)
                {
                    log.Write("Exception: " + ex.Message);
                    Thread.Sleep(60 * 1000);
                }
            } while (!loggedIn);
        }

        protected override bool tryUrl(string url, int maxTries)
        {
            int cnt = maxTries;
            bool success = false;
            do
            {
                cnt--;

                try
                {
                    log.Write("Trying to download from " + url);

                    var bytes_response = client.DownloadData(url);
                    string response = Encoding.UTF8.GetString(bytes_response);

                    Regex regex = new Regex(@"href=""(?<download_inner_link>/download\.php\?id=\d+\&amp;name=.animelayer\.ru._\d+\.torrent)""><b>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
                    Match m = regex.Match(response);
                    if (m.Success)
                    {
                        string download_inner_link = m.Groups["download_inner_link"].Value;
                        string download_link = "http://animelayer.ru" + download_inner_link.Replace("&amp;", "&");
                        downloadToFile(download_link, url);
                        success = true;
                    }
                    else
                    {
                        log.Write("torrent download link not found");
                    }
                }
                catch (Exception ex)
                {
                    log.Write("Exception: " + ex.Message);
                }
                if (!success)
                    Thread.Sleep(60 * 1000);

            } while (!success && cnt > 0);
            return success;
        }

        private void downloadToFile(string url, string referer)
        {
            string path = getPath();

            client.Headers.Add("Referer", referer);
            client.DownloadFile(url, path);
            client.Headers.Remove("Referer");

            log.Write("Torrent file downloaded from " + url + " to " + path);
        }

    }
}
